package com.xyy.saas.payment.adpater.chinabank.constants;

import com.ctrip.framework.apollo.Config;
import com.ctrip.framework.apollo.ConfigChangeListener;
import com.ctrip.framework.apollo.ConfigService;
import com.ctrip.framework.apollo.model.ConfigChangeEvent;
import com.netflix.hystrix.*;
import com.netflix.hystrix.strategy.properties.HystrixPropertiesFactory;
import com.xyy.saas.payment.util.ApolloUtil;
import com.xyy.saas.payment.util.JSONUtils;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.InitializingBean;
import org.springframework.context.annotation.DependsOn;
import org.springframework.stereotype.Component;

import java.util.HashSet;
import java.util.Map;
import java.util.Set;

/**
 * @author wangtianqi
 * @date 2020/8/6 9:55
 */
@Slf4j
@Component
@DependsOn("apolloUtil")
public class ChinaBankHystrixConstants implements InitializingBean {

    public static final String COMMAND_KEY = "DegradedPay4ChinaBankHystrixCommand";

    private static final String CHINA_BANK_HYSTRIX_CONFIG = "china_bank_hystrix_config";

    public static final String SLEEP_WINDOW_KEY = "sleep_window";

    public static final String REQUEST_VOLUME = "request_volume";

    public static final String ERROR_THRESHOLD_PERCENTAGE = "error_threshold_percentage";

    public static final String EXECUTION_TIME_OUT = "execution_time_out";

    public static final String SEMAPHORE_MAX_CONCURRENT = "semaphore_max_concurrent";

    private static Map<String, String> hystrixConfig = JSONUtils.parse2Map(ApolloUtil.getProperty(CHINA_BANK_HYSTRIX_CONFIG), String.class, String.class);

    public static Integer getIntConfigValue(String key) {
        return Integer.parseInt(hystrixConfig.get(key));
    }

    /**
     *  如果状态有改变，清空Hystrix 配置缓存
     */
    public void resetHystrixCache() {
        Hystrix.reset();
    }


    @Override
    public void afterPropertiesSet() throws Exception {
        Set set = new HashSet();
        set.add(CHINA_BANK_HYSTRIX_CONFIG);
        //动态监听配置变化
        Config config = ConfigService.getAppConfig();
        config.addChangeListener(new ConfigChangeListener() {
            @Override
            public void onChange(ConfigChangeEvent changeEvent) {
                hystrixConfig = JSONUtils.parse2Map(ApolloUtil.getProperty(CHINA_BANK_HYSTRIX_CONFIG), String.class, String.class);
                resetHystrixCache();
                log.info("ChinaBankHystrixConstants#onChange change configs success configMap:{}" , JSONUtils.toJSON(hystrixConfig));
            }
        }, set);
    }
}
